import Vue from 'vue'; // 导入vue
import Loading from './index.vue'; // 导入组件

// 将组件作为参数，使用vue提供的全局方法，创建一个构造函数
let LoadingConstructor = Vue.extend(Loading);

let instance;
let positionShoot = 'static';
let heightShoot = 'auto';
let overflowShoot = 'auto';
let root = null;
const openLoading = function (el) {
	root = el ?? this.$el;
	setShoot();
	setLoadingStyle();
	// 初始化实例，此时instance是一个组件实例，但未初始化未完成
	instance = new LoadingConstructor();

	// 完成初始化
	instance.$mount();
	// 将组件添加到根节点body
	root.appendChild(instance.$el);
	instance.show = true;
};

function setLoadingStyle() {
	if (positionShoot === 'static') {
		root.style.position = 'relative';
	}
	let availHeight = window.innerHeight;
	let { x, y, width, height, top, right, bottom, left } =
		root.getBoundingClientRect();
	let root_height = bottom - top;
	let lockheight = Math.min(height, availHeight - y);
	root.style.height = lockheight + 'px';
	root.style.overflow = 'hidden';
}
function setShoot() {
	positionShoot = getComputedStyle(root).position;
	heightShoot = getComputedStyle(root).height;
	overflowShoot = getComputedStyle(root).overflow;
}
function recoverShoot() {
	root.style.overflow = overflowShoot;
	root.style.height = heightShoot;
	root.style.position = positionShoot;
}
const closeLoading = () => {
	instance.show = false;
	recoverShoot();
};
export { openLoading, closeLoading };
